package com.example.demo1.controller;

import com.example.demo1.entity.Book;
import com.example.demo1.service.BookService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


@RestController
@Log4j
public class BookController {
    @Autowired
    private BookService bookService;


    @PostMapping("/book")
    public Map<String, Object> doAdd(@RequestBody Book book) {
        Map<String, Object> result = new HashMap<>();
        try {
            int rows = bookService.addBook(book); // 执行插入，获取受影响行数
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "添加成功");
            } else {
                result.put("success", false);
                result.put("message", "添加失败，未影响任何数据");
            }
        } catch (Exception e) {
            // 捕获异常（如数据库错误），返回失败信息
            result.put("success", false);
            result.put("message", "添加失败：" + e.getMessage());
        }
        return result; // 返回JSON对象，包含success和message
    }



    @DeleteMapping ("/book/{ID}")
    public Map<String, Object> doDelete(@PathVariable("ID")  String ID){
        Map<String, Object> result = new HashMap<>();
        log.info("进入删除程序");

        if (ID == null || ID.isEmpty()) {
            result.put("success", false);
            result.put("message", "书籍ID不能为空");
            return result;
        }

        try {
            int rows = bookService.deleteBook(Integer.parseInt(ID));
            result.put("success", true);
            result.put("message", "删除成功");
            result.put("data", rows);
        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("message", "书籍ID必须是数字");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "服务器错误：" + e.getMessage());
        }

        return result;
    }

    @GetMapping("/book")
    public ArrayList<Book> doList( Book book){
        ArrayList<Book> list = bookService.selectBooks(book);
        log.info("进入查询程序");
       return list;

    }

    @GetMapping("/book/{ID}")
    public Map<String, Object> doSelect(@PathVariable("ID") String ID){
        Map<String, Object> result = new HashMap<>();
        try {
            // 业务逻辑：根据 ID 查询书籍
            Book book = bookService.selectBook(Integer.parseInt(ID));
            result.put("success", true);
            result.put("data", book);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
        }
        return result; // 直接返回 JSON 数据
    }

    @PutMapping("/book")
    public int doUpdate(@RequestBody Book book){
         return bookService.updateBook(book);
    }

}
